package com.leo.springbootmultithreadbasic.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author Leo
 * @version V1.0
 */
public class AccumulateTask extends RecursiveTask<Integer> {

    // 阀值
    private static final int THRESHOLD = 2;

    private int start;

    private int end;

    public AccumulateTask(int start, int end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Integer compute() {

        int sum = 0;

        // 判断任务的规模
        boolean compute = (end - start) <= THRESHOLD;


        //  任务足够小，直接可以计算
        if (compute) {

            for (int i = start; i <= end; i++) {
                sum += i;
            }

        } else {
            // 任务过大，需要切割，Recursive 计算
            int middle = (start + end) / 2;

            // 1.切割成两个子任务
            AccumulateTask leftAccumulateTask = new AccumulateTask(start, middle);
            AccumulateTask rightAccumulateTask = new AccumulateTask(middle + 1, end);

            // 2.依次调用每个子任务的fork()方法执行子任务
            leftAccumulateTask.fork();
            rightAccumulateTask.fork();

            // 3.等待子任务完成，依次调用每个子任务的join()方法
            int leftResult = leftAccumulateTask.join();
            int rightResult = rightAccumulateTask.join();

            // 4.合并子任务执行结果
            sum = leftResult + rightResult;
        }

        return sum;
    }
}
